package com.google.code.avajhelpdesk.utils;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.avajhelpdesk.entities.User;
import com.google.code.avajhelpdesk.persistence.IGenericDAO;
import com.google.code.avajhelpdesk.persistence.IUserDAO;

public class BasicApplicationInitializer {

	private static final Logger logger = LoggerFactory.getLogger(BasicApplicationInitializer.class);
	
	private static final String LOGIN = "admin";

	private IUserDAO userDAO;
	
	private IGenericDAO genericDAO;
	
	private String adminPassword;
	
	private SessionFactory sessionFactory;
	
	private boolean enabled;
	
	public void run() {
		logger.info("Calling appliation initializer");
	
		if (!enabled) {
			logger.info("Application initializer disabled by configuration");
			return;
		}
		
		Session session = null;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			
			if (userDAO.findUser(LOGIN).isEmpty()) {
				logger.info("Creating default admin");
				User admin = new User();
				admin.setPassword(adminPassword);
				admin.setUsername(LOGIN);
				admin.getRoles().add(User.ROLE_ADMIN);
				
				genericDAO.merge(admin);
			}
			
		} finally {
			if (session != null) {
				session.flush();
				session.close();
			}
		}
		
	}

	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public void setAdminPassword(String adminPassword) {
		this.adminPassword = adminPassword;
	}

	public void setGenericDAO(IGenericDAO genericDAO) {
		this.genericDAO = genericDAO;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
